package com.crm.controller.ordersController;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.crm.beans.PurchaseOrderVO;
import com.crm.dao.AttachmentHistoryDAO;
import com.crm.dao.OpportunityDAO;
import com.crm.dao.PODAO;
import com.crm.dao.PartsDAO;
import com.crm.dao.QuotPartsDAO;
import com.crm.dao.QuotationDAO;
import com.crm.dao.SourceCompareDAO;
import com.crm.dao.SourcesDAO;
import com.crm.dao.StockDAO;
import com.crm.dao.SupplierDAO;
import com.crm.entity.AttachmentHistory;
import com.crm.entity.Business;
import com.crm.entity.Opportunity;
import com.crm.entity.PO;
import com.crm.entity.Parts;
import com.crm.entity.QuotParts;
import com.crm.entity.Quotation;
import com.crm.entity.Sourcecompare;
import com.crm.entity.Sources;
import com.crm.entity.StockEntity;
import com.crm.entity.Supplier;
import com.crm.util.Constants;
import com.crm.util.NumToWords;

@Controller
@RequestMapping("/purchaseOrder")
public class PurchaseOrderController {
	protected final Log logger = LogFactory.getLog(getClass());
	@RequestMapping( "/show.do") 
	public ModelAndView show(HttpServletRequest request,HttpSession session, ModelAndView model) throws Exception{
		
		Business bus=(Business)session.getAttribute("business");
		
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		int busid=bus.getBusinessId();
		
			 String status=Constants.ST_GENERATED_SO;
			//OpportunityDAO oprD=new OpportunityDAO();
			List<Opportunity> opr=(List<Opportunity>)OpportunityDAO.getSingleInstance().getByStatus(status, busid);
					logger.info("opportunity list is "+opr);
			  model = new ModelAndView("/jsp/PurchaseOrder.jsp");
			  model.addObject("submenu", "orders");
				model.addObject("menuName","orders");
				model.addObject("opprtunity",opr);
			
				return model;
	}
	@RequestMapping( "/printpo.do") 
	public ModelAndView printpi(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
			AttachmentHistoryDAO atDao=new AttachmentHistoryDAO();
			List<AttachmentHistory> attlist=null;
			try{attlist=atDao.getAllPi(bus.getBusinessId(),Constants.PURCHASE_ORDER);
					logger.info("attachment list is "+attlist);
			}catch(NullPointerException e){
				e.printStackTrace();
			}
			  model = new ModelAndView("/jsp/printPO.jsp");
				model.addObject("attlist",attlist);
				model.addObject("submenu", "orders");
				model.addObject("menuName","orders");
				 
		 
				return model;
	}
	
	
	@RequestMapping(value = "/get_po", method = RequestMethod.GET)
	public String pinting(HttpSession session, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Business bus = (Business) session.getAttribute("business");

		String idno = request.getParameter("quotid");
		int id=Integer.parseInt(idno);
		AttachmentHistoryDAO atDAO = new AttachmentHistoryDAO();
		AttachmentHistory att = atDAO.getAttachmentHistoryByPI(id);
		logger.info("the business id is  " + bus.getBusinessId());
		byte[] pdfReport = att.getFileBlob();
		logger.info("the length of pdf is" + pdfReport.length);
		logger.info("the length of pdf is" + pdfReport.toString());
		ServletOutputStream servletOutputStream = response.getOutputStream();
		String fileName = "quotation.doc";
		response.setHeader("Content-Disposition", "inline; filename=" + fileName);
		response.setContentLength(pdfReport.length);
		servletOutputStream.write(pdfReport);
		servletOutputStream.flush();
		servletOutputStream.close();
		return null;

	}
	@RequestMapping("/generatePO.do")
	public ModelAndView genPO(HttpServletResponse response,HttpServletRequest request,HttpSession session,ModelAndView model) throws Exception{
		
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		int busid=bus.getBusinessId();	
		String refNo=request.getParameter("reflist");
		String suprefno=request.getParameter("sorefno");
		String supplierName=request.getParameter("supplier");
		String sTotal=request.getParameter("total");
		String srowCount=request.getParameter("rowCount");
		String billto=request.getParameter("billto");
		String shipto=request.getParameter("shipto");
		String pono=request.getParameter("pono");
		String tandc=request.getParameter("terms");
		int rowCount=Integer.parseInt(srowCount);
		int total=Integer.parseInt(sTotal);
		
		//OpportunityDAO opDAO=new OpportunityDAO();
		SourcesDAO soDAO=new SourcesDAO();
		SupplierDAO supDAO=new SupplierDAO();
		PartsDAO pDAO=new PartsDAO();
		PODAO podao=new PODAO();
		Opportunity o=OpportunityDAO.getSingleInstance().getByRefNo(busid, refNo);
		//delete previous PO 
		
		
		List<PO> lp=new ArrayList<PO>();
		List<StockEntity> stockList=new ArrayList<StockEntity>();
		StockEntity stock=null;
		List<com.crm.beans.QuotParts> lst=new ArrayList<com.crm.beans.QuotParts>();
		for(int i=0;i<rowCount;i++){
			String partNumber=request.getParameter("partNumber"+(i+1));
			String partid=request.getParameter("partid"+(i+1));
			
			
			String sqty=request.getParameter("qty"+(i+1));
			int qty=Integer.parseInt(sqty);
			
			String sourceName=request.getParameter("source"+(i+1));
			
			String sUnitPrice=request.getParameter("unitPrice"+(i+1));
			float unitPrice=Float.parseFloat(sUnitPrice);
			
			String sSum=request.getParameter("sum"+(i+1));
			float sum=Float.parseFloat(sSum);
			
			String sMoq=request.getParameter("moq"+(i+1));
			int moq=Integer.parseInt(sMoq);
			Supplier s=supDAO.getByName(supplierName,bus.getBusinessId());
			Sources so = null;
			try {
				so=soDAO.getByName(sourceName,bus.getBusinessId());
			} catch (Exception e) {
				e.printStackTrace();
			}
			int srcid=so.getId();
			int supid=s.getId();
			int prtId=Integer.parseInt(partid);
			Parts part=pDAO.getById(o.getId(), prtId,bus.getBusinessId());
			int partid1=part.getPartid();
			PO po=new PO(o.getId(),partid1,qty,srcid,supid,unitPrice,sum,moq,total,bus,new java.util.Date(),suprefno,pono);
			lp.add(po);
			
			com.crm.beans.QuotParts qp=new com.crm.beans.QuotParts(partNumber,""+qty,""+unitPrice ,part.getMake(),""+moq,"","",(i+1)+"",part.getDescription(),sum+"");
			lst.add(qp);
			
			stock=new StockEntity(part,part.getDescription(),qty,new java.util.Date(),qty,0,bus,null);
			stockList.add(stock);
		}
		StockDAO stockdao=new StockDAO();
		stockdao.insertStockList(stockList);
		Opportunity op=OpportunityDAO.getSingleInstance().findById(o.getId(),bus.getBusinessId());
		String addr=bus.getAddress();   
		

		Supplier su=supDAO.getByName(supplierName,bus.getBusinessId());
		
		NumToWords numto=new NumToWords();
		String priceword=numto.convert(total);
		
		Map<String,String> parms = new HashMap<String,String>();
		parms.put("logo", "");
		parms.put("referenceno", suprefno);
		parms.put("CompanyAddress", bus.getBusinessName()+"\n"+addr);
		parms.put("from", o.getBusinessId().getBusinessName());
		parms.put("supplieraddress",su.getAddress());
		parms.put("terms",tandc );
		parms.put("billto",billto);
		parms.put("shipto",shipto);
		parms.put("pono",""+pono);
		parms.put("totalcost",""+total);
		parms.put("totalword","Total  : "+priceword+"  Only");
		session= request.getSession();
		JasperReport report = (JasperReport) JRLoader.loadObject(session.getServletContext().getResourceAsStream("/WEB-INF/classes/reports/po.jasper"));
		JasperPrint prt = JasperFillManager.fillReport(report,parms,new JRBeanArrayDataSource(lst.toArray()));
		byte[] pdfReport = JasperExportManager.exportReportToPdf(prt);
		
		
		JRDocxExporter docExporter=new JRDocxExporter();
		ByteArrayOutputStream docStream=new ByteArrayOutputStream();
		docExporter.setParameter(JRDocxExporterParameter.JASPER_PRINT,prt);
		docExporter.setParameter(JRDocxExporterParameter.OUTPUT_STREAM,docStream);
		docExporter.setParameter(JRDocxExporterParameter.FLEXIBLE_ROW_HEIGHT, Boolean.TRUE);
		docExporter.exportReport();
		pdfReport = docStream.toByteArray();
		
		
		// saving quotation pdf in database
		
		
		AttachmentHistory attachment=new AttachmentHistory("application/msword",bus,Constants.PURCHASE_ORDER,pdfReport,op.getRefNum(),"SAMPLE PO",new java.util.Date());
		AttachmentHistoryDAO atDAO=new AttachmentHistoryDAO();
		
		try{
			podao.deletelastPO(o.getId(),bus.getBusinessId());
			podao.insertList(lp);
			atDAO.insert(attachment);
			String status=Constants.ST_GEN_PO;
			OpportunityDAO.getSingleInstance().updateStatus(busid, status, o.getId());
			System.out.println("Successfully Inserted Purchase Order");
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("Failed to Insert Purchase Order");
		}

	
	
		
		model=new ModelAndView("/jsp/POrderPDF.jsp");
		model.addObject("pono",op.getRefNum());
		model.addObject("resmsg","Sucesssfully Created purcahse Order  With Number"+op.getRefNum());
		model.addObject("submenu", "orders");
		model.addObject("menuName","orders");
		return model;
	}
	@RequestMapping("/search.do") 
	public ModelAndView searchRef(HttpServletRequest request,HttpSession session,ModelAndView model) throws Exception{
		
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		int busid=bus.getBusinessId();
		String refno=request.getParameter("refno");
		String supplierName=request.getParameter("supplierName");
		
		//OpportunityDAO opdao=new OpportunityDAO();
		SupplierDAO sudao=new SupplierDAO();
		QuotationDAO qdao=new QuotationDAO();
		PartsDAO pdao=new PartsDAO();
		SourcesDAO sodao=new SourcesDAO();
		
		int suid=0;
		
		Opportunity op=OpportunityDAO.getSingleInstance().getByRef(refno,bus.getBusinessId());
		int enqid=op.getId();
		try {
			Supplier su=sudao.getSupplier(supplierName,bus.getBusinessId());
			if(su!=null && su.getId()!=0)suid=su.getId();
		} catch (Exception e1) {
			
			e1.printStackTrace();
		}
		Quotation quo=qdao.getQuotByEnq(enqid);
		int quotid=quo.getId();
		QuotPartsDAO qpdao=new QuotPartsDAO();
		SourceCompareDAO scdao=new SourceCompareDAO();
		List<QuotParts> qt=qpdao.getpo(quotid,suid,bus.getBusinessId());
		int total=0;
		List<PurchaseOrderVO> lipo=new ArrayList<PurchaseOrderVO>();
		Iterator<QuotParts> itr=qt.iterator();
		while(itr.hasNext()){
			Object obqp=itr.next();
			
			QuotParts qp=(QuotParts)obqp;

			Parts p=pdao.findByPartIdEnqId(enqid,qp.getPartid().getPartid(),bus.getBusinessId());
			PurchaseOrderVO povo=null;
			if(p!=null) {
				int srcid=0;
				if(qp!=null){
					srcid=qp.getSource();
					
				}
				Sources sd=sodao.findById(srcid,bus.getBusinessId());
				
				String srcname=sd.getSourceName();
				
				Sourcecompare sc=scdao.getPartPrice(enqid, p.getPartid(), suid, busid);
				System.out.println("Unit Price from source compare is: "+sc.getUnitprice());
				Supplier sup=sudao.findById(suid,bus.getBusinessId());
				float sum = (float) (sc.getUnitprice() * qp.getQty());
				
				povo=new PurchaseOrderVO(p.getPartid(),qp.getQty(),srcname,sup.getName(),sc.getUnitprice(),sc.getOfferingPartNo(),sum,qp.getMoq());
				lipo.add(povo);
				total = (int) (total + sum);
			}
		}
		
		String address=bus.getAddress();
		logger.info("Total Value Is:"+total+"\n Opportunity Values Are:"+lipo);
		System.out.println("Total Value Is:"+total+"\n Opportunity Values Are:"+lipo);
		model=new ModelAndView("/jsp/purchaseOrderRes.jsp");	
		model.addObject("submenu", "orders");
		model.addObject("menuName","orders");
		model.addObject("total", total);
		model.addObject("terms",bus.getTandc());
		model.addObject("clientdet",op.getOrganisation());
		model.addObject("division",op.getDivision());
		model.addObject("user",op.getUser());
		model.addObject("address",address);		
		model.addObject("opportunity",lipo);
		return model;
	}
	@RequestMapping( "/searchQuot.do") 
	public @ResponseBody String searchQuot(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		
		Business bus=(Business)session.getAttribute("business");
		
		String refno=req.getParameter("refno");
		
		assert refno!=null:"Reference No In PO Controller Is Null "+refno;
		int busid=bus.getBusinessId();
		//OpportunityDAO oprD=new OpportunityDAO();
		QuotationDAO qdao=new QuotationDAO();
		StringBuilder sb=new StringBuilder();
		
		Opportunity o=OpportunityDAO.getSingleInstance().getByRefNo(busid,refno);
		int enqid=o.getId();
		assert enqid!=0:"Enqid In PO Controller Is:"+enqid;
		List<Quotation> qut=new ArrayList<Quotation>();
		try {
			qut = qdao.getquot(enqid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		Iterator<Quotation> it=qut.iterator();
		while(it.hasNext()){
			Object ob=it.next();
			Quotation q=(Quotation)ob;
			if(q!=null){
			String quot=q.getQuotno();
			sb.append(quot+",");
			}
		}
		assert true;
		
		return sb.toString();
	}
	@RequestMapping( "/searchSuppliers.do") 
	public @ResponseBody String search(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		
		Business bus=(Business)session.getAttribute("business");
		String refno=req.getParameter("refno");
		System.out.println("Reference Number In PO Controller Is:"+refno);
		int busid=bus.getBusinessId();
		//OpportunityDAO oprD=new OpportunityDAO();
		QuotationDAO qdao=new QuotationDAO();
		SupplierDAO sudao=new SupplierDAO();
		StringBuilder sb=new StringBuilder();
			
		Opportunity o=OpportunityDAO.getSingleInstance().getByRefNo(busid,refno);
			int enqid=o.getId();
			System.out.println("Enqid In PO Controller Is:"+enqid);
			Quotation qut=null;
			try {
				qut = qdao.getQuotByEnq(enqid);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			int qtid=qut.getId();
			
			List<Object> liqp=qdao.getquotparts(qtid);
			Iterator<Object> it=liqp.iterator();
			Set<String> setso=new HashSet<String>();
			while(it.hasNext()){
				Object ob=it.next();
				QuotParts qp=(QuotParts)ob;
				int supid=0;
				if(qp!=null){
					try {
						supid=qp.getSupplier();
						System.out.println("Supplier id Is:"+supid);
						if (supid!=0) {
							Supplier su = sudao.findById(supid,bus.getBusinessId());
							System.out.println("Supplier Name Is:"+su.getName());
							String name = su.getName();
							setso.add(name);
							logger.info("Supplier Name Is:"+name);
						}
					} catch (NullPointerException e1) {
						e1.printStackTrace();
					}
				}
			}
			for(String s:setso){
				sb.append(s+",");
			}
			
		return sb.toString();
	}

	@RequestMapping("/get_history.do")
	public String htmlReport(HttpSession session,HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Business bus=(Business)session.getAttribute("business");
		String quotno=request.getParameter("quotid");
		AttachmentHistoryDAO atDAO=new AttachmentHistoryDAO();
		AttachmentHistory att=atDAO.getAttachmentHistoryByEnqno(bus.getBusinessId(),Constants.PURCHASE_ORDER,quotno.trim());
		logger.info("the quotation no is "+quotno.trim());
		logger.info("the business id is  "+bus.getBusinessId());
		byte[] pdfReport =att.getFileBlob();
		logger.info("the length of pdf is"+pdfReport.length);
		logger.info("the length of pdf is"+pdfReport.toString());
		ServletOutputStream servletOutputStream = response.getOutputStream();
		response.setContentType("application/msword");
		response.setContentLength(pdfReport.length);
		servletOutputStream.write(pdfReport);
		
		servletOutputStream.flush();
		servletOutputStream.close(); 
		return null;
	   
	}

}
